package com.ben.multiple.jsoup.model;

import java.util.ArrayList;
import java.util.List;

/**
 * 树模型构建工具
 *
 * @author BenJin Yin
 * @date 2019/10/24
 */
public final class TreeUtils {
    private TreeUtils() {
    }

    /**
     * 构建树
     *
     * @param treeNodeList 所有树节点
     * @param root         根节点 id
     * @param <T>          树 类型
     * @return List<T>
     */
    public static <T extends TreeModel<T>> List<T> buildTree(List<T> treeNodeList, Object root) {
        List<T> treeList = new ArrayList<>();
        if (treeNodeList == null || treeNodeList.size() == 0) {
            return treeList;
        }
        // 数据量超过 10000 时，效率低，手动开启多线程来提高效率
        treeNodeList.parallelStream().filter(obj -> root.equals(obj.getParentId()))
                .forEach(obj -> treeList.add(TreeUtils.findChildren(obj, treeNodeList)));
        return treeList;
    }

    /**
     * @param treeNode     树节点
     * @param treeNodeList 所有树节点
     * @param <T>          树类型
     * @return T
     */
    private static <T extends TreeModel<T>> T findChildren(T treeNode, List<T> treeNodeList) {
        treeNodeList.parallelStream().filter(obj -> treeNode.getId().equals(obj.getParentId()))
                .forEachOrdered(obj -> treeNode.getChildren().add(TreeUtils.findChildren(obj, treeNodeList)));
        return treeNode;
    }
}
